<?php
/**
 * 商品库存查询
 * Created by PhpStorm.
 * User: Min
 * Date: 2018/4/2
 * Time: 11:47
 */

namespace SDXApi\Service\Kingdee;


use SDXApi\Model\GoodsstorageModel;

class GoodsStockQueryService
{
    /**
     * @var KingdeeService
     */
    protected $kingdeeService;

    protected $goodsStorageModel;

    /**
     * GoodsStockQueryService constructor.
     */
    public function __construct()
    {
        $this->kingdeeService = new KingdeeService();
        $this->goodsStorageModel = new GoodsstorageModel();
    }

    /**
     * 获取单个商品库存
     * @author Min
     * @param $wid
     * @param $goods
     * @return mixed
     */
    public function getGoodsStockOne($wid, array $goods)
    {
        $data = $this->handleGoodsStock($wid, $goods['goods_sn'], array($goods));
        return array_shift($data);
    }

    /**
     * 获取多个商品库存
     * @author Min
     * @param $wid
     * @param $goods
     * @return mixed
     */
    public function getGoodsStockList($wid, array $goods)
    {
        $param = $this->getGoodsParam($goods);
        return $this->handleGoodsStock($wid, $param, $goods);
    }

    /**
     * 处理商品库存
     * @author Min
     * @param $wid
     * @param $param
     * @param $goods
     * @return mixed
     */
    protected function handleGoodsStock($wid, $param, $goods)
    {
        if (empty($goods)) {
            return array();
        }

        //获取金蝶库存
        if (in_array($wid, C('K3_Wid'))) {
            $result = $this->kingdeeService->getGoodsStockByGoodsSn($wid, $param);

            if ($result['code'] == 200) {
                foreach ($goods as $key=>$val) {
                    $stock = $result['data'][$val['goods_sn']];
                    $goods[$key]['kingdee_stock'] = isset($stock) ? $stock : 0;
                    $goods[$key]['goods_number'] = isset($stock) ? $stock : 0;
                }
            }

        } else {
            //获取进销存库存
            foreach ($goods as $key => $value) {
                
                if ($goods[$key]['is_presell'] == 0) {

//					获取商品库存
                    $goodsStorage = $this->goodsStorageModel->get_warehous_goods($wid, $value['goods_id']);
                    $goodsNumber = $goodsStorage['practical_num'];
                    $practical_num = $goodsNumber - C('rest_goods_number');

                    if ($practical_num <= 0) {
                        $practical_num = 0;
                    }

//					现售商品使用实际库存
                    $goods[$key]['goods_number'] = $practical_num;
                }
            }

        }

        return $goods;
    }

    /**
     * @author Min
     * @param $goods
     * @return array
     */
    protected function getGoodsParam($goods)
    {
        $param = array();

        foreach ($goods as $key=>$val) {
            $param[$key] = $val['goods_sn'];
        }

        return $param;
    }

}